import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import type { DesignItemStruct } from '@/typings'
import type { FormDefStructure } from '@/api/modules/flow/formDef'
import { defaultProps } from '@/components/form-engine/form-props/default'
import { getPermissionConfig as getPermissionDefaultConfig } from '@/components/form-engine/comps/config'
import { flowDefApi } from '@/api/modules/flow/flowDef'

export const useFlowStore = defineStore('form', () => {
  const designData = ref({} as FormDefStructure) //表单结构数据
  const form = ref({ ...defaultProps } as Record<string, any>) //表单属性
  const comps = ref([] as DesignItemStruct[]) //组件列表
  const currComp = reactive({ index: -1, comp: {} as DesignItemStruct }) //当前组件
  const changeActive = ref(0) //变更表单版本标志structureId， 更新激活的标志变更一次加1
  const tasks = ref([] as any[]) //流程节点

  //激活组件
  function activeComp(index: number) {
    currComp.index = index
    currComp.comp = index >= 0 ? comps.value[index] : ({} as DesignItemStruct)
  }
  //获取组件属性值
  function getProps(index?: number) {
    if (index === undefined) {
      return currComp.comp.propsData
    } else {
      return comps.value[index].propsData
    }
  }

  //获取组件权限值
  function getPermission(index?: number) {
    let permission
    if (index === undefined) {
      permission = currComp.comp.permission
    } else {
      permission = comps.value[index].permission
    }
    return permission || {}
  }
  //设置组件权限值
  function setPermission(data: any, index?: number) {
    if (index === undefined) {
      currComp.comp.permission = data
    } else {
      comps.value[index].permission = data
    }
  }
  //获取组件权限配置
  function getPermissionConfig(index?: number) {
    let pConfig
    if (index === undefined) {
      pConfig = getPermissionDefaultConfig(currComp.comp.config)
    } else {
      pConfig = getPermissionDefaultConfig(comps.value[index].config)
    }
    return pConfig || {}
  }

  function setData(data: FormDefStructure) {
    designData.value = data
    if (data) {
      if (data.formJson) {
        const json = JSON.parse(data.formJson)
        form.value = Object.assign(defaultProps, json.form)
        comps.value = json.comps
      } else {
        if (data.formName) {
          form.value = Object.assign(defaultProps, { title: data.formName })
        } else {
          form.value = { ...defaultProps }
        }
        comps.value = []
      }
    }
    //获取当前流程tasks
    findTasks()
  }
  function findTasks() {
    flowDefApi.findUserTask(designData.value.processDefKey, designData.value.processDefId).then((resp: any) => {
      if (resp.success) {
        tasks.value = resp.data
        const firstTask = tasks.value.filter(t => t.order == 0)
        if (firstTask && tasks.value.length > 0) {
          form.value.firstTaskId = firstTask[0].id //记录第一个节点ID，在表单申请时会用到
        }
      }
    })
  }

  function getFormJson() {
    return JSON.stringify({ comps: comps.value, form: form.value })
  }

  function checkFormJson() {
    if (
      comps.value.filter(comp => {
        return comp.config.compTag.startsWith('s-approve-user-name')
      }).length > 1
    ) {
      ElMessage.error('同一类审批组件最多只能添加一个')
      return false
    }
    if (
      comps.value.filter(comp => {
        return comp.config.compTag.startsWith('s-approve-time')
      }).length > 1
    ) {
      ElMessage.error('同一类审批组件最多只能添加一个')
      return false
    }
    if (
      comps.value.filter(comp => {
        return comp.config.compTag.startsWith('s-approve-comment')
      }).length > 1
    ) {
      ElMessage.error('同一类审批组件最多只能添加一个')
      return false
    }
    return true
  }

  function updateActiveStructure(newStructureId: string) {
    if (newStructureId !== designData.value.structureId) {
      changeActive.value = changeActive.value + 1
    }
  }

  return {
    designData,
    tasks,
    form,
    comps,
    currComp,
    changeActive,
    activeComp,
    getProps,
    getPermission,
    setPermission,
    getPermissionConfig,
    setData,
    getFormJson,
    checkFormJson,
    updateActiveStructure
  }
})
